package com.e.dianshang.controller;


import com.e.dianshang.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@Api(value = "执行图片上传的控制器",tags = "图片上传接口的api")
public class UploadController {

    @PostMapping("/upload")
    @ApiOperation(value = "图片上传的接口",notes = "图片上传",httpMethod = "POST",response = String.class)
    public Map<String,Object> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
    String [] f={"png","jpg","jpeg","gif"};

    JsonResult jsonResult=new JsonResult();
    //查看文件大小是否符合规定
    long size = multipartFile.getSize();
        if (size>1048576){
        jsonResult.setCode("0");
        jsonResult.setMsg("文件过大");
        return jsonResult.getValues();
    }

    //获取文件的名字
    String originalFilename = multipartFile.getOriginalFilename();
    //获取文件名的后缀
    String subfix= originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // System.out.println(subfix);
    //判断是否是合适的文件类型
        for (int a=0;a>f.length;a++) {
        if (subfix.equals(f[a])) {
            jsonResult.setCode("0");
            jsonResult.setMsg("文件类型不符合");
            return jsonResult.getValues();
        }
    }
    //给文件一个新的文件名字
    String newName = UUID.randomUUID().toString().replace("-", "") + "." + subfix;
    //获取当前程序的根路径,保存在本地静态目录下

    //String path=request.getServletContext().getRealPath("E:/Projects-new/dianshang/eureka-goods/src/main/webapp/");

        //System.out.println(path);

//    String dest = "E:/Projects-new/dianshang/eureka-goods/src/main/webapp/static/img/"+newName;
        String dest = "E:/Projects-new/dianshang/eureka-goods/src/main/webapp/static/img/"+newName;
        System.out.println(dest);

    //把文件保存在目标路径(上传阿里云)
//    String dest="/static/img/upload/"+newName;
//    System.out.println("dest:"+dest);


    //创建目标路径
    File file=new File(dest);

    //用multipartFile写入文件
        try {
        multipartFile.transferTo(file);
    } catch (IOException e) {
        throw e;
    }finally {
            jsonResult.put("file",newName);
            jsonResult.setCode("1");
            jsonResult.setMsg("图片上传成功");
            jsonResult.setData(dest);
            return jsonResult.getValues();
    }

    }
}
